package com.xneure.code.algorithm;

import java.util.Arrays;

public class AllPermutation{
	private Object[] data;
	private int last;
	private int movePoint = 1;
	private int moveLevel;
	private int loop;
	private int loopMax;
	private Object swapVar;

	public AllPermutation(){
	}

	public AllPermutation(Object... original){
		setData(original);
	}

	public void setData(Object[] data){
		if(data.length < 3){
			throw new RuntimeException("排列组合长度不能小于：3");
		}
		this.data = Arrays.copyOf(data,data.length);
		this.last = data.length - 1;
		loopMax = last - 1;
	}

	public void reset(){
		movePoint = 1;
		loop = 0;
		moveLevel = 0;
	}

	public boolean hashNext(){
		boolean b = moveLevel == last && loop == loopMax && movePoint == last;
		if(b){
			return false;
		}else{
			if(movePoint++ == last){
				movePoint = 2;
				if(loop++ == loopMax){
					++moveLevel;
					loop = 0;
					swapVar = data[moveLevel];
					data[moveLevel] = data[0];
					data[0] = swapVar;
				}
			}
			return true;
		}
	}

	public Object[] next(){
		swapVar = data[movePoint];
		data[movePoint] = data[movePoint - 1];
		data[movePoint - 1] = swapVar;
		return data;
	}

	public static void main(String[] args){
		AllPermutation ap = new AllPermutation(1,2,3,4);
		for(int i = 0;i < 1;i++){
			long time = System.nanoTime();
			while(ap.hashNext()){
				System.out.println(Arrays.toString(ap.next()));
			}
			ap.reset();
			System.out.println(System.nanoTime() - time);
		}
	}
}
